

<template>
  <!-- 导航部分 -->
  <el-row class="row">
    <el-col :span="24">
      <el-link>返回</el-link>
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>新增商品</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
  </el-row>

  <el-row class="row">
    <el-col :span="24">
      <el-form :model="item" label-width="auto" style="max-width: 1000px">
        <el-form-item label="选择类别">
          <el-button @click="showChooseItemWin" type="success">{{currentCat.catName}}</el-button>
        </el-form-item>
        <el-form-item label="选择规格">
          <el-button @click="showChooseItemSpeWin" type="success">选择规格</el-button>
        </el-form-item>
        <el-form-item label="商品标题">
          <el-input v-model="item.itemTitle" />
        </el-form-item>
        <el-form-item label="商品卖点">
          <el-input v-model="item.itemSellPoint" />
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="item.itemPrice" />
        </el-form-item>
        <el-form-item label="商品库存">
          <el-input v-model="item.itemNum" />
        </el-form-item>
        <el-form-item label="条形码">
          <el-input v-model="item.itemBarcode" />
        </el-form-item>

        <el-form-item label="商品图片">
          <el-upload
              v-model:file-list="fileList"
              :action="uploadImageUrl"
              list-type="picture-card"
              :on-success="handleAvatarSuccess"
              :on-remove="handleRemove"
              :on-preview="handlePictureCardPreview"
              name="uploadFile"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog v-model="imageDialogVisible">
            <img w-full :src="imageDialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品详情">
          <div style="border: 1px solid #ccc">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="valueHtml"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>

        <el-form-item label="">
          <el-button type="primary" @click="doAddItem">提交</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
  <!-- 选择商品类别 -->
  <el-dialog
      v-model="chooseItemCatDialog"
      title="选择商品类别"
      width="500"
  >
    <el-tree
        :data="cats"
        :props="defaultProps"
        @node-click="chooseItemCat"
    />
  </el-dialog>


  <!-- 选择商品规格 -->
  <el-dialog
      v-model="chooseItemSpeDialog"
      title="选择商品规格"
      width="60%"
  >

    <!-- 搜索栏 -->
    <el-row class="row">
      <el-col :span="24">
        <el-form inline :model="speQuery" label-width="auto" >
          <el-form-item label="规格名称">
            <el-input v-model="speQuery.speName" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
                v-model="speQuery.status"
                placeholder="全部状态"
                size="large"
                style="width: 240px"
            >
              <el-option :key="0" label="全部" :value="0"/>
              <el-option :key="1" label="正常" :value="1"/>
              <el-option :key="2" label="禁用" :value="2"/>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="loadSpes" type="info">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 列表 -->
    <el-row class="row">
      <el-col :span="24">
        <el-table :data="spes" stripe  border style="width: 100%">
          <el-table-column label="是否选择">
            <template #default="scope">
              <el-switch @click="checkSpe(scope.row)" v-model="scope.row.isCheck" />
            </template>
          </el-table-column>
          <el-table-column prop="speName" label="规格名称" />
          <el-table-column prop="createTime" label="创建时间"  />
          <el-table-column prop="status" label="状态"  >
            <template #default="scope">
              <el-tag v-if="scope.row.status == 1" type="success">正常</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240" >
            <template #default="scope">
              <el-button size="small" @click="" type="primary">查看规格项</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 分页栏 -->
    <el-row class="row">
      <el-col :span="24">
        <el-pagination @change="changePage" background layout="prev, pager, next" :total="total" />
      </el-col>
    </el-row>
  </el-dialog>
</template>
<script setup>
import {useRouter} from 'vue-router'
import itemRequest from '../../api/item.js';
import itemCatRequest from '../../api/item-cat.js';
import speRequest from '../../api/spe.js';
import { ElMessage } from 'element-plus'
import {ref,onBeforeUnmount, shallowRef,onMounted, reactive} from 'vue';

import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
let router = useRouter();
// 属性----------------
// 表单相关属性
let item = ref({});
let currentCat = ref({catName:'选择类别'});// 当前表单中的商品类型对象
// -- 选择商品类目的弹窗相关属性 --
let chooseItemCatDialog = ref(false);
let cats = ref([]);// 保存所有的商品类型
const defaultProps = {
  children: 'children',
  label: 'catName',
}

// wangEditor相关属性声明
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')
// 工具栏的配置，这里是默认配置
const toolbarConfig = {}
// 编辑器配置
const editorConfig = {                       // JS 语法
  MENU_CONF: {},
  placeholder:'请输入商品详情....'
}
// 上传图片的配置
editorConfig.MENU_CONF['uploadImage'] = {
  server: 'http://localhost:11011/cms/wangUpload', // 上传图片的地址
  fieldName:'uploadFile',// 上传图片的域的名字
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

// --  选择规格相关属性  --
let chooseItemSpeDialog = ref(false);
let speQuery = reactive({});// 封装搜索条件
let spes = ref([]);// 规格数据列表
// 分页相关属性
let total = ref(0);
let currentPage = ref(1);
let limit = ref(10);
let checkSpeIds = [];
// 图片上传的相关属性
let fileList = ref([]);// 图片列表
let uploadImageUrl = ref("http://localhost:8080/upload");
let imageDialogVisible = ref(false);//放大图片的弹窗标志
let imageDialogImageUrl = ref('');// 此刻要放大的图片的url
let uploadImages = ref([]);// 保存我们上传的所有的图片地址


// 申明函数
/**
 * 提交按钮事件
 */
function  doAddItem(){
  // 判断所有的数据是否已经符合要求  .....
  // 组织数据
  item.value.itemPrice = item.value.itemPrice * 100;
  // 类型编号
  item.value.catId = currentCat.value.catId;
  // 规格列表
  item.value.itemSpe = checkSpeIds;
  // 图片列表
  item.value.images = uploadImages.value;
  // 详情描述
  item.value.itemDesc = valueHtml.value;
  // 提交
  itemRequest.save(item.value,res=>{
    if(res.code == '200'){
      ElMessage({
        type:"success",
        message:"添加商品成功"
      })
      // 跳转到列表页面
      router.push("/home/goods-list");
    }else{
      ElMessage({
        type:"error",
        message:"添加商品失败"
      })
    }
  })
}

/**
 * 删除照片墙中的一张图片
 * @param uploadFile 图片对象
 */
function handleRemove(uploadFile){
  let url = uploadFile.response.msg;
  uploadImages.value = uploadImages.value.filter(imageUrl=> imageUrl != url);
}
/**
 * 上传图片成功的事件
 * @param res 上传成功之后响应的结果
 */
function handleAvatarSuccess(res){
  let url = res.msg;
  uploadImages.value.push(url);
}
/**
 * 放大图片的函数
 * @param uploadFile 要放大的图片
 */
function handlePictureCardPreview(uploadFile){
  imageDialogImageUrl.value = uploadFile.url;
  imageDialogVisible.value = true;
}
/**
 * 选择商品规格开关的点击事件
 * @param speData
 */
function checkSpe(speData){
  console.log(speData)
  if(speData.isCheck){
    // 给数组中添加这个id
    checkSpeIds.push(speData.speId);
  }else{
    // 从数组中删除这个id
    checkSpeIds = checkSpeIds.filter(id=>id != speData.speId);
  }
  console.log(checkSpeIds)
}
/**
 * 表单中选择规格的按钮事件
 */
function showChooseItemSpeWin(){
  loadSpes();
  chooseItemSpeDialog.value = true;
}
function chooseItemCat(data){
  console.log(data)
  if(data.parent == 0){// 判断是否点击了叶子节点
    currentCat.value = data; // 记录叶子节点为当前选中的类型
    // 关闭窗体
    chooseItemCatDialog.value = false;
  }
}

/**
 * 表单中选择类目的按钮事件
 */
function showChooseItemWin(){
  loadAllCat();
  chooseItemCatDialog.value = true;
}
/**
 * 加载所有的商品类型
 */
function loadAllCat(){
  itemCatRequest.queryAll(res=>{
    cats.value = res.data;
  })
}

/**
 * 加载所有的spe
 */
function loadSpes(){
  speRequest.queryByPage(currentPage.value,limit.value,speQuery,res=>{
    console.log(res)
    spes.value = res.data.records;
    total .value = res.data.total;
  })
}

</script>
<style scoped>

</style>